package cn.teleware.api.config;

import cn.teleware.api.annotation.NoResult;
import cn.teleware.api.dto.Result;
import cn.teleware.api.dto.ResultCode;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : hongsw
 * @date : 2020-11-12-9:16
 * @descriptions :
 */
@RestControllerAdvice
public class GlobalExceptionHandler implements ResponseBodyAdvice<Object> {
    /**
     * 对校验数据错误的接口进行异常处理
     *
     * @param e 异常
     * @return cn.teleware.api.dto.Result<java.util.List < java.lang.String>>
     * @author hongsw
     * @date 2020/11/12 14:54
     **/
    @ExceptionHandler(BindException.class)
    public Result<List<String>> methodArgumentNotValidExceptionHandler(BindException e) {
        List<String> allErrorMessages = new ArrayList<>();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for (ObjectError allError : allErrors) {
            allErrorMessages.add(allError.getDefaultMessage());
        }
        return new Result<>(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage(), allErrorMessages);
    }

    /**
     * 判断是否需要封装统一响应体
     * 含有@NoResult的注解不封装
     * 已经是Result的响应体的不封装(基本为异常信息)
     *
     * @param methodParameter 请求
     * @param aClass          未知
     * @return boolean
     * @author hongsw
     * @date 2020/11/12 14:51
     **/
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return !(methodParameter.getParameterType().equals(Result.class) || methodParameter.hasMethodAnnotation(NoResult.class));
    }

    /**
     * 对Controller的返回值进行统一封装响应体
     *
     * @param result             Controller的返回值
     * @param methodParameter    未知
     * @param mediaType          未知
     * @param aClass             未知
     * @param serverHttpRequest  未知
     * @param serverHttpResponse 未知
     * @return java.lang.Object
     * @author hongsw
     * @date 2020/11/12 14:52
     **/
    @Override
    public Object beforeBodyWrite(Object result, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return new Result<>(result);
    }
}
